/**
 * 
 */
package networkinterface;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author Michael & Pierre
 *
 */
/**
 * Thread used to send a file
 */
public class SendFileThread extends Thread {
	
	private static JavaNI javaNI;
	
	private File myFile;
	private String dest;
	private int port;
	
	/**
	 * @param myFile file which will be sent
	 * @param dest address of the recipient of the file
	 * @param port remote port where the file will be sent
	 * @param javaNI network interface of the system
	 */
	public SendFileThread(File myFile, String dest, int port, JavaNI javaNI) {
		SendFileThread.javaNI = javaNI;
		this.myFile = myFile;
		this.dest = dest;
		this.port = port;
	}
	
	public void run() {
		
		Socket mySocket;
		BufferedInputStream inFile;
		BufferedOutputStream outFile = null;
		
		try {
			
			mySocket = new Socket(InetAddress.getByName(dest), port);
			inFile = new BufferedInputStream(new FileInputStream(myFile));
			outFile = new BufferedOutputStream(mySocket.getOutputStream());
			byte[] octets = new byte[1024];
			int num;
			while ((num = inFile.read(octets, 0, 1024)) != -1) {
			  outFile.write(octets, 0, num);
			}
			
			outFile.flush();
			outFile.close();
			mySocket.close();
			javaNI.fileSent();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				outFile.flush();
				outFile.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
